package com.blt.car.me;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.blt.car.R;
import com.blt.car.base.BaseTitleBarActivity;
import com.blt.car.base.ViewHolder;
import com.blt.car.pay.AuthResult;
import com.blt.car.pay.OrderInfoUtil2_0;
import com.blt.car.pay.PayResult;
import com.blt.car.utils.Uiutils;
import com.blt.car.widget.NoScrollGridView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import blt.app_core.api.base.CoreEvent;
import blt.app_core.api.base.CoreManager;
import blt.app_core.api.purse.PayApi;
import blt.app_core.api.purse.bean.ChargeVo;
import blt.app_core.api.purse.bean.PayVo;
import blt.app_core.log.Logger;

/**
 * Created by
 * xgp on 2017/6/20.
 */

public class ChargeActivity extends BaseTitleBarActivity implements View.OnClickListener {

    public static final String CHARGE_AMOUNT = "charge_amount";
    private NoScrollGridView gridView;
    private static final int WEI_XIN = 2 << 3;
    private static final int ALIPAY = 2 << 6;

//    String vouchers[] = {"1000", "500", "300", "200", "100", "50"};
//    String sends[] = {"50", "30", "20", "10", "5", "0"};

    private CheckBox cbWeixin;
    private CheckBox cbPay;
    private TextView tvAmount;
    private ChargeAdapter chargeAdapter;

    private int payChannel;
    private long amount;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ChargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ChargeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(ChargeActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(ChargeActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_charge;
    }

    @Override
    protected void initData() {
        amount = getIntent().getExtras().getLong(CHARGE_AMOUNT);
        CoreManager.getCore(PayApi.class).getVoucherList();
    }

    @Override
    protected void initView(ViewHolder holder) {
        mTitleBar.setTitle("充值");
        gridView = holder.get(R.id.charge_gridview);
        chargeAdapter = new ChargeAdapter();
        gridView.setAdapter(chargeAdapter);

        holder.get(R.id.charge_btn_add_amount);
        tvAmount = holder.get(R.id.charge_tv_amount);
        tvAmount.setText(getResources().getString(R.string.my_balance, amount));
        holder.setOnClickListener(this, R.id.charge_btn_add_amount);
        cbPay = holder.get(R.id.charge_cb_pay);
        cbWeixin = holder.get(R.id.charge_cb_weixin);
        cbPay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                payChannel = 0;
                if (isChecked) {
                    cbWeixin.setChecked(false);
                    payChannel = ALIPAY;
                }
            }
        });
        cbWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                payChannel = 0;
                if (isChecked) {
                    cbPay.setChecked(false);
                    payChannel = WEI_XIN;
                }
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.charge_btn_add_amount:
                createOrder();
                break;

        }
    }

    private void createOrder() {
        ChargeVo vo = chargeAdapter.getSelectItem();
        if (vo == null) {
            toastShort("请选择充值金额");
            return;
        }

        if (payChannel == 0) {
            toastShort("请选择充值平台");
            return;
        }
        String payType;
        if (payChannel == WEI_XIN) {
            payType = "weixin";
        } else {
            payType = "alipay";
        }
        amount += vo.chargeAmt / 100;
        Uiutils.progressShow(this);
        CoreManager.getCore(PayApi.class).createOrder(payType, (int) vo.chargeAmt, "充值");
    }

    @CoreEvent(coreClientClass = PayApi.class)
    public void onCreateOrder(PayVo payVo) {
        Uiutils.progressCancel();
//        toastShort("充值成功");
        apliy(payVo);
        tvAmount.setText(getResources().getString(R.string.my_balance, amount));
        CoreManager.notifyClients(PayApi.class, PayApi.onChargeSuccess, amount);
    }


    private void apliy(PayVo payVo) {
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(
                payVo);
        final String param = OrderInfoUtil2_0.buildOrderParam(params);
        Logger.d("param:" + param);
//        String sign = OrderInfoUtil2_0.getSign(params, payVo.sign, false);
//        final String orderInfo = param+"&sign="+payVo.sign;
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ChargeActivity.this);
                Map<String, String> result = alipay.payV2(param, true);
                Logger.d("result: " + result);
                Message msg = Message.obtain();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @CoreEvent(coreClientClass = PayApi.class)
    public void onCharge(List<ChargeVo> data) {
        chargeAdapter.add(data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CoreManager.removeClient(PayApi.class);
    }

    class ChargeAdapter extends BaseAdapter {
        private SparseArray<Boolean> selects = new SparseArray<>();
        private List<ChargeVo> chargeVos = new ArrayList<>();

        public void add(List<ChargeVo> data) {
            chargeVos.clear();
            chargeVos.addAll(data);
            for (int i = 0; i < data.size(); i++) {
                selects.put(i, false);
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return chargeVos.size();
        }

        @Override
        public Object getItem(int position) {
            return chargeVos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View v, ViewGroup parent) {
            if (v == null) {
                v = LayoutInflater.from(ChargeActivity.this).inflate(R.layout.item_charge, parent, false);
            }

            final LinearLayout container = (LinearLayout) v.findViewById(R.id.item_charge_container);
            final TextView voucher = (TextView) v.findViewById(R.id.item_charge_voucher);
            TextView tvSend = (TextView) v.findViewById(R.id.item_charge_send);

            ChargeVo chargeVo = chargeVos.get(position);
            long charge = chargeVo.chargeAmt / 100;
            long send = chargeVo.giveAmt / 100;
            voucher.setText(getResources().getString(R.string.voucher_charge, charge));
            tvSend.setText(getResources().getString(R.string.voucher_send, send));


            if (selects.get(position)) {
                container.setBackgroundResource(R.color.text_color_orange);
                voucher.setTextColor(getResources().getColor(R.color.text_color));
                tvSend.setTextColor(getResources().getColor(R.color.text_color));
            } else {
                container.setBackgroundResource(R.color.bg_gray);
                voucher.setTextColor(getResources().getColor(R.color.text_color_black));
                tvSend.setTextColor(getResources().getColor(R.color.text_color_orange));
            }

            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < chargeVos.size(); i++) {
                        selects.put(i, false);
                        if (i == position) {
                            selects.put(i, true);
                        }
                    }
                    notifyDataSetChanged();
                }
            });
            return v;
        }


        private ChargeVo getSelectItem() {
            for (int i = 0; i < chargeVos.size(); i++) {
                if (selects.get(i)) {
                    return chargeVos.get(i);
                }
            }
            return null;
        }

    }


}
